package cn.hd01.weixin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.repository.entity.BankCards;
import cn.hd01.repository.entity.Customer;
import cn.hd01.repository.entity.CustomerBankCard;
import cn.hd01.service.BankCardsService;
import cn.hd01.service.CustomerBankCardService;
import cn.hd01.service.CustomerService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.auth.AuthType;
import cn.hd01.web.util.WebHelper;
import cn.hd01.weixin.model.Result;

@Controller
@RequestMapping("/weixin/bank")
@Auth(AuthType.WECHAT)
public class WXBankController {

	@Autowired
	private CustomerService cusomterService;

	@Autowired
	private CustomerBankCardService bankCardService;

	@Autowired
	private BankCardsService bankCardsService;

	@RequestMapping(path = "", method = RequestMethod.GET)
	public String index(Model m) {
		Customer customer = cusomterService.findByOauthId(WebHelper.currentWXOauth().getId());
		m.addAttribute("banks", bankCardService.findByCustomerId(customer.getId()));
		return "weixin/supplier/listbank";
	}

	@RequestMapping(path = "/add", method = RequestMethod.GET)
	public String addBank(Model m) {
		Customer customer = cusomterService.findByOauthId(WebHelper.currentWXOauth().getId());
		m.addAttribute("customerId", customer.getId());
		return "weixin/supplier/addbank";
	}

	@ResponseBody
	@RequestMapping(path = "/add", method = RequestMethod.POST)
	public Result submitBank(CustomerBankCard bc) {
		BankCards card = bankCardsService.findByBankCardBin(bc.getBankCardNum().substring(0, 6));
		if (card == null) {
			return new Result(false, "无法识别的银行卡号");
		}
		
		bc.setBankCardType(card.getBankCardType());
		bc.setBankName(card.getBankName());
		if(bankCardService.findByDefaultCard(bc.getCustomerId()) == null){
			bc.setIsDefault(true);
		}

		bankCardService.save(bc);
		return new Result();
	}

}
